package me.xiaosiqi.server_info.tool;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 发送消息到Server酱
 */
@Service
@Slf4j
public class ServerChanService {
    @Value("${spring.ServerChan}")
    String ServerChanURL;//Server酱API

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送消息到Server酱
     * @param title 主题
     * @param desp  内容
     * @return 是否成功
     */
    public boolean sendMsg(String title, String desp) {
        LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("title", title);
        map.add("desp", desp);
        try {
            log.debug("发送消息到Server酱：{}", map);
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(ServerChanURL, map, String.class);
            String body = stringResponseEntity.getBody();
            log.debug("发送到Server酱的回信：{}", body);
            JSONObject jsonObject = JSONUtil.parseObj(body);
            if (jsonObject.getInt("code") == 0) {
                return true;
            } else {
                log.error("发送消息到Server酱失败：{}", body);
                return false;
            }
        } catch (Exception e) {
            log.error("验证码发送失败：", e);
            return false;
        }
    }
}